package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryController {
    @Autowired
    CategoryService categoryService;

    private HashMap cgMap = new HashMap();

    //用于添加分类
    @PostMapping
    public R sava(@RequestBody Category category) {
        log.info("category:{}", category);
        categoryService.save(category);
        return R.success("新增分类成功");
    }

    //用于分页查询
    @GetMapping("/page")
    public R page(int page, int pageSize) {
        //分页构造器
        Page<Category> pageInfo = new Page<>(page, pageSize);
        //条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //添加排序条件，根据sort进行排序
        queryWrapper.orderByAsc(Category::getSort);

        //分页查询
        categoryService.page(pageInfo, queryWrapper);

        List<Category> records = pageInfo.getRecords();
        long total = pageInfo.getTotal();
        cgMap.clear();
        cgMap.put("records", records);
        cgMap.put("total", total);
        return R.success(cgMap);
    }

    //用于删除数据
    @DeleteMapping
    public R deleteById(long id){
        log.info("要删除的分类id为{}",id);
       // categoryService.removeById(id);
        categoryService.remove(id);
        return R.success("删除成功!");
    }

    //用于修改菜品
    @PutMapping
    public R update (@RequestBody Category cg){
        log.info("修改分类信息：{}",cg);
        categoryService.updateById(cg);
        return R.success("修改成功");
    }

    //用于查询菜品数据
    @GetMapping("/list")
    public R list ( Integer type){
        LambdaQueryWrapper<Category> wq=new LambdaQueryWrapper<>();
        wq.eq(type!=null,Category::getType,type)
          .orderByAsc(Category::getSort)
          .orderByDesc(Category::getUpdateTime);

        List<Category> list = categoryService.list(wq);

        return R.success(list);
    }


}
